package com.kaishengit.web;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.kaishengit.entity.Product;
import com.kaishengit.service.ProductService;
import com.kaishengit.util.StringUtil;

public class ProductServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private ProductService service = new ProductService();
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String task = request.getParameter("task");
	
		if(StringUtil.StringIsEmpty(task)){
			show(request,response);
		}else if("insert".equals(task)){
			add(request,response);
		}else if("del".equals(task)){
			del(request,response);
		}
	}

	private void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		int id = StringUtil.StringToInteger(request.getParameter("id"));
		service.delete(id);
		response.sendRedirect("product.jspx");
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		Product product = new Product();
		product.setProdid(request.getParameter("id"));
		product.setName(request.getParameter("name"));
		product.setPrice(StringUtil.StringToFloat(request.getParameter("price")));
		product.setEnable(StringUtil.StringToBoolean(request
				.getParameter("enable")));
		service.save(product);
		response.sendRedirect("product.jspx");
		
	}

	private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Gson json = new Gson();
		List<Product> products = service.findAll();
		String jsonString = json.toJson(products);
		out.print(jsonString);
		
		out.flush();
		out.close();
		
	}
}
